<template>
  <el-dialog
    :title="title"
    v-model="props.params.visible"
    width="1100px"
    append-to-body
    :before-close="cancel"
    v-loading="loading"
  >
    <el-form
      :model="addForm"
      ref="addRef"
      :inline="true"
      :rules="addRules"
      label-width="80px"
    >
      <el-form-item label="维修日期" prop="maintenanceTime">
        <el-date-picker
          style="width: 220px"
          v-model="addForm.maintenanceTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="维修日期"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="维修类型" prop="maintenanceType">
        <el-input
          v-model="addForm.maintenanceType"
          placeholder="请输入维修类型"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="维修项目" prop="maintenanceProject">
        <el-input
          v-model="addForm.maintenanceProject"
          placeholder="请输入维修项目"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="故障描述" prop="maintenanceDesc">
        <el-input
          v-model="addForm.maintenanceDesc"
          placeholder="请输入故障描述"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="维修人" prop="maintenancePersonId">
        <el-select
          v-model="addForm.maintenancePersonId"
          filterable
          clearable
          remote
          reserve-keyword
          placeholder="请选择维修人"
          :remote-method="getUserOption"
          :loading="userLoading"
          style="width: 220px"
          @change="handleChooseUser"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修提成" prop="maintenanceCommissions">
        <el-input-number
          :min="0"
          v-model="addForm.maintenanceCommissions"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="维修工费" prop="maintenanceCost">
        <el-input-number
          :min="0"
          v-model="addForm.maintenanceCost"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="ref">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.ref"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品型号" prop="model">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.model"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select
          v-model="addForm.brand"
          filterable
          reserve-keyword
          clearable
          remote
          :remote-method="getItemBrand"
          :disabled="basicInfo"
          default-first-option
          placeholder="请选择品牌"
          style="width: 220px"

        >
          <el-option
            v-for="item in item_brand"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收价格" prop="recyclePrice">
        <el-input-number
          :disabled="basicInfo"
          v-model="addForm.recyclePrice"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="回收编码" prop="recycleCode">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.recycleCode"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <!-- <el-form-item label="商品正面" prop="file1">
        <el-upload
          v-model:file-list="fileList"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="true"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品背面" prop="file2">
        <el-upload
          v-model:file-list="fileListBack"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="true"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addRegister,
  getRegister,
  updateRegister,
} from "@/api/maintenance/register";
import { optionSelect } from "@/api/system/skesItem";
import { userOptionSelect } from "@/api/system/user";
import useUserStore from "@/store/modules/user";
import { listData } from "@/api/system/dict/data";

import { computed, ref, watchEffect } from "vue";
const props = defineProps({
  params: Object,
  visible: Boolean,
  options: Array,
});
const emits = defineEmits(["update:visible", "refresh"]);
const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const title = computed(() =>
  props.params.type === "add" ? "新增维修登记" : "修改维修登记"
);
const dateRange = ref([]);
const addForm = ref({
  maintenanceTime: undefined,
  maintenanceType: undefined,
  maintenanceProject: undefined,
  maintenanceDesc: undefined,
  maintenanceCommissions: undefined,
  maintenanceCost: undefined,
  ref: undefined,
  model: undefined,
  brand: undefined,
  maintenancePersonId: userStore.id,
  maintenancePerson: userStore.nickName,
  maintenancePersonName: userStore.name,
  recyclePrice: undefined,
});
const addRules = {
  itemId: [{ required: true, message: "商品不能为空", trigger: "blur" }],
  maintenanceTime: [
    { required: true, message: "维修日期不能为空", trigger: "blur" },
  ],
  maintenanceDesc: [
    { required: true, message: "故障描述不能为空", trigger: "blur" },
  ],
  maintenancePersonId: [
    { required: true, message: "维修人不能为空", trigger: "blur" },
  ],
  maintenanceCommissions: [
    { required: true, message: "维修提成不能为空", trigger: "blur" },
  ],
  maintenanceCost: [
    { required: true, message: "维修工费不能为空", trigger: "blur" },
  ],
};
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
watchEffect(() => {
  const { visible, type } = props.params;
  if (visible) getDetail();
});

/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: i.id,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
        recyclePrice: i.recyclePrice,
      };
    });
    remoteLoading.value = false;
  }
}
function handleChooseItem(id) {
  const { recyclePrice } = itemOptions.value.find((i) => i.value === id) || {
    recyclePrice: undefined,
  };
  addForm.value.recyclePrice = recyclePrice;
}

/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        nickName,
        userName,
      };
    });
    userLoading.value = false;
  }
}
function handleChooseUser(userId) {
  const { nickName, userName } = userOptions.value.find(
    (i) => i.value === userId
  ) || {
    nickName: undefined,
    userName: undefined,
  };
  addForm.value.maintenancePerson = nickName;
  addForm.value.maintenancePersonName = userName;
}
getItemOption(" ");
getUserOption(" ");
/** 获取商品详情 */
const fileList = ref([]);
const fileListBack = ref([]);
function getDetail() {
  getRegister(props.params.id).then((response) => {
    const { maintenancePersonId, watchImageUrl, watchImageUrlBack, brand } =
      response.data;
    fileList.value[0] = { url: watchImageUrl };
    fileListBack.value[0] = { url: watchImageUrlBack };
    const mid =
      typeof maintenancePersonId === "number"
        ? maintenancePersonId + ""
        : maintenancePersonId;
    addForm.value = response.data;
    if (props.params.type === "edit") {
      addForm.value.maintenancePersonId = mid;
    } else {
      addForm.value.maintenancePersonId = userStore.id;
      addForm.value.maintenancePerson = userStore.nickName;
      addForm.value.maintenancePersonName = userStore.name;
    }
    getItemBrand(brand);
  });
}

/** 品牌 */
const brandLoading = ref(false);
const item_brand = ref([]);
async function getItemBrand(query) {
  if (query) {
    brandLoading.value = true;
    let label = "";
    let val = "";
    if (isNaN(query)) {
      label = query;
    } else {
      val = query;
    }
    const { rows } = await listData({
      pageNum: 1,
      pageSize: 10,
      dictType: "item_brand",
      dictValue: val,
      dictLabel: label,
    });
    item_brand.value = rows.map((i) => {
      const { dictValue, dictLabel } = i;
      return {
        value: dictValue,
        label: dictLabel,
      };
    });
    brandLoading.value = false;
  }
}
const basicInfo = ref(true);
/** 重置表单  */
function reset() {
  addForm.value.recyclePrice = undefined;
  addForm.value.maintenancePerson = undefined;
  proxy.resetForm("addRef");
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      if (props.params.type === "add") {
        addRegister(addForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增回收登记成功");
          emits("refresh");
          cancel();
        });
      } else {
        updateRegister(addForm.value).then(
          (response) => {
            proxy.$modal.msgSuccess("修改回收登记成功");
            emits("refresh");
            cancel();
          }
        );
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  reset();
  emits("update:visible", false);
}
</script>
